import { jsapi, viewUtils } from '@/utils/arcgis';
import { addPlotLyr, updatePlotLyr, getPlotLyrByProjIdAndLyrId } from '@/services/bookmarkServices';

export async function exhydratGraphicLayer(layerId, projectId,schemeIndex) {
  const view = await viewUtils.isViewReady();
  const sketchLayer = view.map.findLayerById(layerId);
  let graphics = []
  try {
    graphics = sketchLayer.graphics.map(graphic => {
      if(!graphic.uindex) graphic.uindex = schemeIndex
      console.log('graphic',graphic)
      return graphic.toJSON();
    });
    const [lyrInfo] = await getPlotLyrByProjIdAndLyrId(projectId, layerId);
    const { id } = lyrInfo;
    await updatePlotLyr({
      layerName: `${projectId}_${layerId}`,
      description: '',
      graphics: JSON.stringify(graphics),
      id,
    });
  } catch (error) {
    await addPlotLyr({
      projectId,
      layerName: `${projectId}_${layerId}`,
      description: '',
      graphics: JSON.stringify(graphics),
      layerId,
    });
  }
  // window.localStorage.setItem(layerId + projectId, JSON.stringify(graphics));
  return true;
}

export async function hydratGraphicLayer(layer, projectId) {
  let graphics = [];
  const [Graphic_] = await jsapi.load(['esri/Graphic']);
  try {
    // @ts-ignore
    const [lyrInfo] = await getPlotLyrByProjIdAndLyrId(projectId, layer.id);
    // const data = JSON.parse(window.localStorage.getItem(layer.id + projectId));
    const data = JSON.parse(lyrInfo.graphics);
    console.log(data, '-----------');
    graphics = data.map(graphicJSON => {
      return Graphic_.fromJSON(graphicJSON);
    });
    layer.addMany(graphics);
  } catch (error) {
    // console.error(error);
    console.log(error, '=-=====================================');
  }

  return true;
}
